<template>
  <view class="education-info-detail">
    <!-- 使用通用展示组件（只读模式） -->
    <DetailDisplayList
      :config="config"
      :list="educationList"
      :loading="loading"
      :show-actions="false"
    >
      <!-- 自定义文件展示 -->
      <template #file-display="{ field, item }">
        <view
          v-for="(fileId, index) in getEducationFileIds(item[field.key])"
          :key="fileId"
          class="file-attachment"
          @tap="
            () =>
              previewEducationFile(
                fileId,
                `${field.fileConfig?.fileNamePrefix || '文件'}${index + 1}`,
              )
          "
        >
          <uni-icons type="paperplane" size="16" color="#059669" />
          <text class="file-name"
            >{{ field.fileConfig?.fileNamePrefix || "文件"
            }}{{ index + 1 }}</text
          >
          <text class="preview-hint">点击预览</text>
        </view>
      </template>
    </DetailDisplayList>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import SysHrInterviewRequestBillApi from "../api/index";
import type {
  IEducationResponse,
  ISubTableSearchRequest,
} from "../api/interface";
import DetailDisplayList from "./DetailDisplayList.vue";
import { educationDisplayConfig } from "./detailDisplayConfig";

const api = SysHrInterviewRequestBillApi();

// Props
interface Props {
  personId?: string;
  readonly?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  personId: "",
  readonly: false,
});

// 数据
const loading = ref(false);
const educationList = ref<IEducationResponse[]>([]);

// 详情展示配置（只读模式）
const config = ref({
  ...educationDisplayConfig,
  addButtonText: "",
});

// 加载学习经历列表
const loadEducationList = async () => {
  if (!props.personId) {
    console.log("学习经历组件：缺少personId");
    return;
  }

  loading.value = true;

  try {
    const requestData: ISubTableSearchRequest = {
      Limit: 50,
      Page: 1,
      PersonId: props.personId,
      SortInfo: null,
    };

    console.log("学习经历组件：获取学习经历请求参数:", requestData);
    const res = await api.getEducationList(requestData);
    console.log("学习经历组件：学习经历接口返回:", res);

    if (res && res.Data && Array.isArray(res.Data)) {
      educationList.value = res.Data;
      console.log("学习经历组件：获取学习经历成功:", educationList.value);
    } else {
      educationList.value = [];
      console.log("学习经历组件：学习经历数据为空");
    }
  } catch (error) {
    console.error("学习经历组件：获取学习经历异常:", error);
    educationList.value = [];
    uni.showToast({
      title: "获取学习经历失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 获取学历证书文件ID数组
const getEducationFileIds = (
  fileIds: { FileId: string }[] | string[] | string | undefined,
): string[] => {
  if (!fileIds) return [];

  // 如果是对象数组格式 [{ FileId: "xxx" }]
  if (
    Array.isArray(fileIds) &&
    fileIds.length > 0 &&
    typeof fileIds[0] === "object" &&
    "FileId" in fileIds[0]
  ) {
    return (fileIds as { FileId: string }[])
      .map((item) => item.FileId)
      .filter((id: string) => id.trim());
  }

  // 如果是字符串数组，直接返回
  if (Array.isArray(fileIds))
    return (fileIds as string[]).filter((id: string) => id.trim());

  // 如果是字符串，分割后返回（兼容旧数据）
  if (typeof fileIds === "string" && fileIds) {
    return fileIds.split(",").filter((id: string) => id.trim());
  }

  return [];
};

// 预览学历证书文件
const previewEducationFile = async (fileId: string, fileName: string) => {
  if (!fileId) {
    uni.showToast({
      title: "文件不存在",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({
      title: "加载中...",
    });

    await api.previewFile(fileId, fileName);

    uni.showToast({
      title: "文件加载成功",
      icon: "success",
    });
  } catch (error) {
    console.error("预览学历证书文件失败:", error);
    uni.showToast({
      title: "文件预览失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

// 监听personId变化，加载学习经历
watch(
  () => props.personId,
  (newId) => {
    if (newId) {
      loadEducationList();
    }
  },
  { immediate: true },
);

// 暴露方法供父组件调用
defineExpose({
  loadEducationList,
});
</script>

<style lang="scss" scoped>
.education-info-detail {
  // 保留文件附件样式，因为在自定义插槽中使用
  .file-attachment {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 8rpx 12rpx;
    background: #f0f9ff;
    border: 1rpx solid #e0f2fe;
    border-radius: 6rpx;
    cursor: pointer;
    transition: all 0.3s ease;

    &:active {
      background: #e0f2fe;
      transform: scale(0.98);
    }

    .file-name {
      font-size: 24rpx;
      color: #374151;
      font-weight: 500;
      flex: 1;
    }

    .preview-hint {
      font-size: 20rpx;
      color: #6b7280;
    }
  }
}
</style>
